package com.bsoft.gol.hbs.bbpmessagel.channel;

import com.bsoft.gol.hbs.bbpmessagel.enums.MsgTypeEnum;
import com.bsoft.gol.hbs.bbpmessagel.template.WxMiniSubscribeData;
import com.bsoft.gol.hbs.bbpmessagel.template.WxMiniSubscribeMessage;
import com.bsoft.gol.hbs.bbpmessagel.util.Constants;
import com.bsoft.gol.hbs.bbpmessagel.util.WeChatMessageApiUtil;
import ctd.message.Message;
import ctd.net.rpc.json.JSONResponseBean;
import com.bsoft.gol.hbs.dao.HiSysMsgTplDao;
import hcn.base.message.HiSysMsgTplEntity;
import hcn.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import ssdev.bbp.message.channel.MessageChannel;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @description:微信小程序订阅消息发送实现
 * @author: zhengcb10708
 * @create: 2022-03-13 16:59
 **/
public class WeChatMiniSubscribeMsgSendService implements MessageChannel {
    @Autowired
    private HiSysMsgTplDao hiSysMsgTplDao;
    @Value("${miniprogramState}")
    private String miniprogramState;
    @Override
    public JSONResponseBean sendMessage(String miniOpenid, Message message) {
        JSONResponseBean baseResponse= new JSONResponseBean();
        Map<String, String> extras = message.getExtras();
        //miniAccessToken 小程序订阅消息token
        if(!isEmpty(extras)&&!isEmpty(extras.get("miniOpenid"))&&!isEmpty(extras.get("miniAccessToken"))){
            //处理微信小程序订阅消息模板配置
            handleWechatMiniSubscribe(extras);
            if (StringUtils.hasText(extras.get("wechatMiniSubscribeJson"))) {
                return WeChatMessageApiUtil.sendMiniSubscribeMessage(extras.get("wechatMiniSubscribeJson"),
                        extras.get("miniAccessToken"));
            }
            baseResponse.setCode(ResultCode.ERROR);
            baseResponse.setMsg("微信小程序订阅消息消息体为空");
        }else {
            baseResponse.setCode(ResultCode.ERROR);
            baseResponse.setMsg("微信公众号入参不全");
            return baseResponse;
        }
        return baseResponse;
    }

   /**
    * @Describe:处理微信小程序订阅消息模板配置
    * @Param: [extras]
    * @Return: void
    * @Author: zhengcb10708
    * @Date: 2022/3/13 17:12
    */
    private void handleWechatMiniSubscribe(Map<String, String> extras){
        if(extras.containsKey("cd")&&!isEmpty(extras.get("cd"))&&!isEmpty(extras.get("miniOpenid"))){
            List<HiSysMsgTplEntity> hiSysMsgTplEntityList=hiSysMsgTplDao.findHiSysMsgTplListByParams(MsgTypeEnum.WECHAT_APPLETS_SUBSCRIBE_MSG.getCode(),extras.get("cd"));
            if(!isEmpty(hiSysMsgTplEntityList)){
                WxMiniSubscribeMessage subscribeMessage =
                        WxMiniSubscribeMessage.builder().toUser(extras.get("miniOpenid")).templateId(getHiSysMsgTplValue(hiSysMsgTplEntityList, Constants.APPLETSTEMPLATEID))
                                .page(handleConfigureVariable(getHiSysMsgTplValue(hiSysMsgTplEntityList,Constants.APPLETSTEMPLATEJUMPPAGE),
                                        extras)).miniprogramState(miniprogramState)
                                .lang(getHiSysMsgTplValue(hiSysMsgTplEntityList,Constants.APPLETSLANG)).build();
                for(HiSysMsgTplEntity hiSysMsgTplItem:hiSysMsgTplEntityList){
                    subscribeMessage.addData(new WxMiniSubscribeData(hiSysMsgTplItem.getTplKey(),
                            handleConfigureVariable(hiSysMsgTplItem.getTplVal()==null?"":hiSysMsgTplItem.getTplVal(),
                                    extras)));
                }
                extras.put("wechatMiniSubscribeJson",subscribeMessage.toJson());
            }
        }
    }
    /**
     * @Describe: 处理配置里面的变量信息
     * @Param: [configureKeyword, extra]
     * @Return: java.lang.String
     * @Author: zhengcb10708
     * @Date: 2022/3/13 15:02
     */
    private String handleConfigureVariable(String configureKeyword, Map<String,String> extra) {
        //遍历消息体变量列表，进行变量赋值
        if (!isEmpty(extra) && StringUtils.hasText(configureKeyword)) {
            for (Map.Entry<String, String> entry : extra.entrySet()) {
                //这里处理变量只处理##【】包裹的，避免出现非变量文本被替换
                String msgVariableKey = entry.getKey();
                if (msgVariableKey != null
                        && ((msgVariableKey.startsWith("#") && msgVariableKey.endsWith("#")) || (msgVariableKey.startsWith("【") && msgVariableKey.endsWith("】")))) {
                    configureKeyword = configureKeyword.replaceAll(msgVariableKey,
                            entry.getValue() == null ? "" :
                                    entry.getValue());

                }
            }
        }
        return configureKeyword;
    }
    //获取微信公众号模板维护指定的值
    private String getHiSysMsgTplValue(List<HiSysMsgTplEntity> hiSysMsgTplEntityList, String hiSysMsgTpKeyWord){
        if(!isEmpty(hiSysMsgTplEntityList)){
            for(HiSysMsgTplEntity hiSysMsgTplEntity:hiSysMsgTplEntityList){
                if(hiSysMsgTplEntity.getTplKey().equals(hiSysMsgTpKeyWord)){
                    return hiSysMsgTplEntity.getTplVal();
                }
            }
        }
        return null;
    }
    //校验空值
    private static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof CharSequence) {
            return ((CharSequence) obj).length() == 0;
        }
        if (obj instanceof Collection) {
            return ((Collection<?>) obj).isEmpty();
        }
        if (obj instanceof Map) {
            return ((Map<?, ?>) obj).isEmpty();
        }
        if (obj.getClass().isArray()) {
            return Array.getLength(obj) == 0;
        }
        return false;
    }
}
